package com.heima.app.gateway.filter;


import com.heima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description: 认证过滤器
 * @Version: V1.0
 */
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.判断当前 是否是登录 请求；如果是登录 则 放行
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String reqUrl = request.getURI().getPath();//获取请求url
        //2.判断是否为 /login/in
        if (reqUrl.contains("/login")){
            //2.1 当 是 请求 路径 时 放行
            return  chain.filter(exchange);
        }

        //3.获取请求头 jwt token 信息
        String jwtToken = request.getHeaders().getFirst("token");
        //3.1 判断 token 是否为空 为空 的 话 提醒 用户 先登录
        if (StringUtils.isEmpty(jwtToken)){
            //如果 不存在 则 提醒 登录
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete(); //不放行
        }

        //4. 判断令牌信息 是否正确
        try{
            Claims claims = AppJwtUtil.getClaimsBody(jwtToken);
            //4.1获取 tonken 值
            //-1有效 0有效 1过期 2过期
            int verifyToken = AppJwtUtil.verifyToken(claims);
            //4.2 如果 token 值大于0 拦截
            if (verifyToken>0){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete(); //不放行
            }
            //4.3 解析JWT 令牌信息
            Integer id= claims.get("id",Integer.class);
            log.info("header token id:{}, URL:{}", id, request.getURI().getPath());

            //5. 将 令牌信息 传递到 各个微服务
            ServerHttpRequest serverHttpRequest = request.mutate().
                    headers( httpHeaders ->{
                        httpHeaders.add("userId", String.valueOf(id));
                    } ).build();
            exchange.mutate().request(serverHttpRequest).build();

        }catch (Exception e){
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return  response.setComplete();
        }

        // 6 返回结果
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
